package com.ft.adbix.core;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import com.ft.adbix.core.ad.AdBixAdLoader;
import com.ft.adbix.core.config.AdBixInitConfig;
import com.ft.adbix.core.listener.ADBixInitListener;
import com.ft.adbix.core.service.DelayedRequestService;
import com.ft.adbix.utils.data.gather.common.DataGatherManager;
import com.ft.adbix.utils.data.gather.entity.DataGatherConfig;
import com.ft.adbix.utils.data.gather.listener.DeviceDataGatherListener;
import com.ft.adbix.utils.data.gather.util.DataGatherUtil;
import com.ft.adbix.utils.data.gather.util.LogUtils;
import com.ft.adbix.utils.data.gather.util.device.ProcessUtil;
import com.ft.adbix.utils.data.synchronize.entity.CustomPackageInfo;
import com.ft.adbix.utils.data.synchronize.entity.DeviceData;
import com.ft.adbix.utils.data.synchronize.entity.ProcessData;
import com.ft.adbix.utils.download.DownloadUtils;
import com.ft.adbix.utils.http.HttpHelper;
import com.ft.adbix.utils.http.listener.HttpListener;
import com.ft.adbix.utils.http.request.RequestUtil;
import com.ft.adbix.utils.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.ft.adbix.utils.universalimageloader.core.ImageLoader;
import com.ft.adbix.utils.universalimageloader.core.ImageLoaderConfiguration;
import com.ft.adbix.utils.universalimageloader.core.assist.QueueProcessingType;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

public class ADBixSdk {

    private Context context;
    private boolean isInit = false;
    private AdBixInitConfig adBixInitConfig;
    private AdBixAdLoader adLoader;

    private ADBixSdk() {

    }

    private static final class InstanceHolder {
        static final ADBixSdk instance = new ADBixSdk();
    }

    public static ADBixSdk getInstance() {
        return InstanceHolder.instance;
    }

    public boolean isInit(){
        return isInit;
    }

    public Context getContext() {
        return context;
    }

    public void init(@NonNull Context context, AdBixInitConfig initConfig, ADBixInitListener listener){
        this.context = context;
        adBixInitConfig = initConfig;

        try{
            DataGatherManager.getInstance().init(context, new DataGatherConfig.Builder().setCanGetPhoneStateInfo(adBixInitConfig.isCanUsePhoneState())
                    .setCanGetWifiInfo(adBixInitConfig.isCanUseWifiState())
                    .setCanUseLocation(adBixInitConfig.isCanUseLocation())
                    .setCanUseOaid(true).build());
            if (!ProcessUtil.isMainProcess()){
                return;
            }
            DataGatherUtil.gatherDeviceData(new DeviceDataGatherListener() {
                @Override
                public void onDeviceDataGather(String crashData, DeviceData deviceData, List<CustomPackageInfo> installPackageList, List<ProcessData> appProcessList) {
                    adLoader = new AdBixAdLoader(context);
                    HttpHelper.post(HttpHelper.ADBIX_BASE_URL+"/appInit", RequestUtil.transInitParams(initConfig.getAppName()), new HttpListener() {
                        @Override
                        public void onRequestStart() {

                        }

                        @Override
                        public void onRequestFailed(int code, String error) {
                            listener.onFailed(error);
                        }

                        @Override
                        public void onRequestSuccess(String result) {
                            LogUtils.i("ad request result = "+result);
                            startService(context);
                            try{
                                JSONObject jsonObject = new JSONObject(result);
                                int code = jsonObject.getInt("code");
                                LogUtils.i("ad request code = "+code);
                                if (code!=200){
                                    String message = jsonObject.getString("message");
                                    listener.onFailed(message);
                                }else{
                                    isInit = true;
                                    listener.onInitComplete();
                                }
                            }catch (Exception e){
                                listener.onFailed("未知异常");
                            }

                        }

                        @Override
                        public void onRequestSuccess(String result, Map<String, List<String>> responseHeader) {

                        }
                    });
                }
            });

            ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
            config.threadPriority(Thread.NORM_PRIORITY - 2);
            config.denyCacheImageMultipleSizesInMemory();
            config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
            config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
            config.tasksProcessingOrder(QueueProcessingType.LIFO);
            ImageLoader.getInstance().init(config.build());

            DownloadUtils.getInstance().init(context);


        }catch (Exception e){
            e.printStackTrace();
            listener.onFailed("初始化失败");
        }

    }

    private void startService(Context context){
        Intent serviceIntent = new Intent(context, DelayedRequestService.class);
        context.startService(serviceIntent);
    }

    public void init(@NonNull Context context, ADBixInitListener listener) {
        init(context,AdBixInitConfig.defaultConfig(),listener);
    }

    public AdBixInitConfig getConfig(){
        return this.adBixInitConfig;
    }

    public AdBixAdLoader getAdLoader(){
        return adLoader;
    }

    public String getSdkVersion(){
        return "1.0.0";
    }

}
